package org.oschina.helper.activemq;

import java.util.HashMap;
import java.util.Map;

import javax.jms.Destination;

import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.apache.activemq.pool.PooledConnectionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Component;

@Component
public class ActiveMQHelper {

	@Autowired
	private PooledConnectionFactory pooledConnectionFactory;
	
	private final long RECEIVE_TIMEOUT=100;
	
	private final Map<String,JmsTemplate> JMS_TEMPLATES=new HashMap<String,JmsTemplate>();
	
	/**
	 * 获得模板
	 * @param key
	 * @param jmsType
	 * @return
	 */
	public JmsTemplate getTemplate(String key,JmsType jmsType)
	{
		JmsTemplate jmsTemplate=JMS_TEMPLATES.get(key);
		if(jmsTemplate==null)
		{
			jmsTemplate=new JmsTemplate();
			jmsTemplate.setConnectionFactory(pooledConnectionFactory);
			jmsTemplate.setDefaultDestination(getDestination(key,jmsType));
			jmsTemplate.setReceiveTimeout(RECEIVE_TIMEOUT);
			JMS_TEMPLATES.put(key, jmsTemplate);
		}
		return jmsTemplate;
	}
	
	/**
	 * 获得目的地
	 * @param key
	 * @param jmsType
	 * @return
	 */
	private Destination getDestination(String key,JmsType jmsType)
	{
		Destination destination=null;
		
		switch (jmsType)
		{
			case QUEUE:
			{
				destination=new ActiveMQQueue(key);
				break;
			}
			case TOPIC:
			{
				destination=new ActiveMQTopic(key);
				break;
			}
		}
		
		return destination;
	}
}